<template>
  <div class="danye">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>酒品管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{ dialogTitle }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div style="width: 90%; padding: 1rem">
      <el-button style="margin: 2rem 0" type="primary" @click="retrenye"
        >返回</el-button
      >
      <el-form
        ref="wineForm"
        label-position="left"
        :model="wineData"
        label-width="90px"
      >
        <el-form-item label="名称" prop="wname">
          <el-input v-model="wineData.wname"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="wineData.type"
            @change="tiy"
            ref="sect"
            clearable
            placeholder="请选择商品类型"
          >
            <el-option
              v-for="item in types"
              :key="item.name"
              :label="item.name"
              :value="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="heiImage">
          <el-upload
            :disabled="isDisabled"
            :show-file-list="false"
            class="avatar-uploader"
            :action="uploadUrls"
            :auto-upload="false"
            ref="myUpload"
          >
            <div class="avatar-uploader">
              <div class="avatar" @click="onsavat">
                <img
                  v-if="wineData.heiImage"
                  :src="wineData.heiImage"
                  style="width: 100%; height: 100%"
                />
                <i v-else class="el-icon-plus add avatar-uploader-icon"></i>
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="产地" prop="origin">
          <el-input v-model="wineData.origin"></el-input>
        </el-form-item>
        <el-form-item label="年份" prop="vintageYear">
          <el-input v-model="wineData.vintageYear"></el-input>
        </el-form-item>
        <el-form-item label="酒精含量" prop="alcoholContent">
          <el-input v-model="wineData.alcoholContent"></el-input>
        </el-form-item>
        <el-form-item label="容量（ml）" prop="volumeMl">
          <el-input v-model="wineData.volumeMl"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="wineData.price"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="stockQuantity">
          <el-input v-model="wineData.stockQuantity"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="wineData.description"></el-input>
        </el-form-item>
        <!-- :on-change="handleUpload" -->

        <el-form-item prop="imageUrl" label="图片集">
          <el-upload
            :disabled="false"
            :action="uploadUrls"
            :multiple="true"
            :limit="5"
            :auto-upload="true"
            :file-list="listImg"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-error="handleError"
            :on-success="handleMultiAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
          <el-button style="margin: 1rem 0" type="primary" @click="onopen()"
            >裁剪</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('wineForm')"
            >保存</el-button
          >
          <el-button @click="resetForm('wineForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <VueCropper
      @croppedImage="handleCroppedImage"
      ref="CropperRef"
    ></VueCropper>
  </div>
</template>

<script>
import { winelist } from "@/api/winetype";
import { addWine, updateWine } from "@/api/wine";
import { Message } from "element-ui";
import VueCropper from "@/components/croppe";
export default {
  components: {
    VueCropper,
  },
  props: {
    currentWine: {
      type: Object,
      default: () => ({}),
    },
    mode: {
      type: String,
      default: "add",
    },
  },
  data() {
    return {
      imageUrl: "",
      listImg: [],
      types: [],
      wineData:
        this.mode === "edite" ? { ...this.currentWine } : { imageUrl: "" },
      formRules: {
        // 定义表单校验规则，根据实际需要进行修改
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
      },
      dialogImageUrl:
        "https://pic1.zhimg.com/80/v2-366c0aeae2b4050fa2fcbfc09c74aad4_720w.jpg",
      dialogVisible: false,
      uploadUrls: process.env.VUE_APP_BASE_API + "/system/upload/upload",
      width: null,
      height: null,
      charts: [],
      isDisabled: true,
    };
  },
  mounted() {
    this.getWineType();
    this.edUeriMAG();
  },
  computed: {
    dialogTitle() {
      return this.mode === "add" ? "添加酒品" : "编辑酒品";
    },
  },
  components: {
    VueCropper,
  },
  methods: {
    edUeriMAG() {
      if (this.mode === "edite" && this.wineData.imageUrl) {
        // 拆分字符串并提取基础 URL 和文件名
        this.listImg = this.wineData.imageUrl.split(",").map((item) => {
          const matches = item.match(
            /http:\/\/185\.232\.92\.15:8008\/(.*?)\.(jpg|png)/
          );
          if (matches && matches.length >= 3) {
            const baseUrl = matches[0];
            const filename = matches[1];
            const extension = matches[2];
            return {
              url: item,
              name: `${baseUrl}${filename}.${extension}`,
            };
          } else {
            return {
              url: item,
              name: item, // 如果没有匹配到基础 URL 和文件名，则将原始字符串作为名称
            };
          }
        });
      }
    },
    uDataTostring(request) {
      this.wineData.imageUrl = this.charts.join(",");
    },
    handleCroppedImage(previewImg) {
      // 在这里处理从子组件传递过来的数据
      console.log("Cropped image:", previewImg);
      const name = `image_${new Date().getTime()}`;
      this.listImg.push({
        name: name, // 图片名字，可以根据实际情况设置
        url: `${previewImg}`, // 裁剪后的图片地址
      });
      this.dialogImageUrl = previewImg;
    },
    handleMAvatarSuccess(response, file, fileList) {
      console.log(response, file, fileList);
      // 处理上传成功后的逻辑
      // if (response.code === 200) {
      //   // 上传成功，更新界面显示或保存上传结果
      //   this.wineData.imageUrl = response.data.imageUrl;
      //   // 其他逻辑...
      // } else {
      //   // 上传失败，处理错误情况
      //   this.$message.error("上传失败：" + response.message);
      // }
    },
    onsavat() {
      this.$refs.CropperRef.smode = "one";
      this.$refs.CropperRef.option.autoCropWid = 337.5;
      this.$refs.CropperRef.option.autoCropHeight = 144;
      this.$refs.CropperRef.option.fixedNumber = [337.5, 144];
      this.$refs.CropperRef.option.maxImgSize = 337.5;
      this.$refs.CropperRef.dialogVisible = true;
      console.log(this.$refs.CropperRef.previewImg);
    },
    onopen() {
      this.$refs.CropperRef.smode = "tuw";
      this.$refs.CropperRef.option.autoCropWid = 375;
      this.$refs.CropperRef.option.autoCropHeight = 330;
      this.$refs.CropperRef.option.fixedNumber = [375, 330];
      this.$refs.CropperRef.option.maxImgSize = 375;
      this.$refs.CropperRef.dialogVisible = true;
    },
    onCropperReady() {
      console.log("Cropper ready");
    },
    handleRemove(file) {
      //移除
      console.log(file, "jjjj");
    },

    handleMultiAvatarSuccess(res, file) {
      // 多张图片上传成功后的处理函数
      const files = res.data.file;
      this.listImg.push(files); // 将图片地址保存到数组中
      this.dialogImageUrl = files; // 显示预览图片
      this.dialogVisible = false; // 显示预览对话框
      console.log(this.listImg, "显示预览对话框");
    },
    handlePictureCardPreview(file) {
      //预览
      console.log(file);
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleError(err, file) {
      //上传失败
      console.log(err, "jjjj");
    },
    beforeAvatarUpload(file) {
      // 校验图片格式(也可直接用 accept 属性限制如：accept="image/png,image/jpg,image/jpeg,image/gif")
      const isFormat =
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg" ||
        file.type === "image/gif";
      // 校验图片大小
      const is200K = file.size / 1024 / 1024;
      console.log("jjjjjjjj");
      if (!isFormat) {
        this.$message.error("上传图标只能为 jpg、png、gif 格式!");
        return false;
      } else if (!is200K) {
        this.$message.error("上传图标大小不能超过 200K!");
        return false;
      } else {
        // 校验图片宽高大小
        const isSize = new Promise((resolve, reject) => {
          const width = 375;
          const height = 330;
          const _URL = window.URL || window.webkitURL;
          const img = new Image();
          img.onload = () => {
            // 限制宽高必须为 18*18 像素
            const valid =
              img.width == width &&
              img.height == height &&
              img.width === img.height;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传图标尺寸限制为375*330比例");
            return Promise.reject();
          }
        );
        return isFormat && is200K && isSize;
      }
    },
    tiy(e) {
      this.currentWine.type = null;
      this.currentWine.type = e;
      console.log(this.currentWine.type);
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    retrenye() {
      this.$router.push("/wine/wine");
    },
    async getWineType() {
      const res = await winelist();
      this.types = res.data.list.records;
    },
    handleUpload(file, fileList) {
      this.imageUrl = URL.createObjectURL(file.raw);
      const uploadedFile = fileList.find((item) => item.name === file.name);
      console.log(uploadedFile);
      if (
        uploadedFile &&
        uploadedFile.response &&
        uploadedFile.response.data.url
      ) {
        // 从后端返回的数据中提取文件地址，并保存到你的数据中
        const fileUrl = uploadedFile.response.data.url;
        this.wineData.imageUrl = fileUrl;
      }
    },
    async save() {
      const param = {
        ...this.wineData,
      };
      const res = await addWine(param);
      if (res.code == 200) {
        Message("提交成功");
      } else {
        Message("提交失败");
      }
    },
    async edite() {
      const param = {
        ...this.wineData,
      };
      const res = await updateWine(param);
      if (res.code == 200) {
        Message("提交成功");
      } else {
        Message("提交失败");
      }
    },
    // 提交表单的方法
    submitForm(formName) {
      this.uDataTostring();
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 在这里可以处理表单验证通过后的逻辑
          // 比如提交表单数据到后端
          if (this.mode === "add") {
            this.save();
          } else if (this.mode === "edite") {
            this.edite();
          }
        } else {
          return false;
        }
      });
    },
    // 重置表单的方法
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.avatar-uploader {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 337.5px;
  height: 114px;
  line-height: 100px;
  vertical-align: top;
  text-align: center;
  .el-upload {
    height: 100px !important;
  }
}
.avatar {
  width: 337.5px;
  height: 114px;
  line-height: 100px;
  border-radius: 6px;
}
.add {
  font-size: 3rem;
  line-height: 2;
  color: #bbb6b6;

  text-align: center;
}
/* Add styles if needed */
</style>
